﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace PrVyd.Zakladni_tridy
{
    class InvoiceManager
    {
        public List<Invoice> Invoices
        {
            get { return FindAllInvocies(); }
        }

        public bool CreateInvoice(Invoice invoice)
        {
            try
            {
                XDocument doc = DatabaseManager.LoadDBX();
                XElement xElem = doc.Element("invoices");
                xElem.Add(invoice);
                DatabaseManager.SaveDB(doc);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool UpdateInvoice(Invoice invoice)
        {
            XDocument doc = DatabaseManager.LoadDBX();
            try
            {
                foreach (XElement item in doc.Descendants("invoice"))
                    if (item.Attribute("id").Equals(invoice.Number.ToString()))
                    {
                        item.Parent.Add(invoice);
                        item.Remove();
                        DatabaseManager.SaveDB(doc);
                        return true;
                    }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }

        public bool DeleteInvoice(long id)
        {
            XDocument doc = DatabaseManager.LoadDBX();
            try
            {
                foreach (XElement item in doc.Descendants("invoice"))
                    if (item.Attribute("id").Equals(id.ToString()))
                    {
                        item.Remove();
                        DatabaseManager.SaveDB(doc);
                        return true;
                    }
            }
            catch (Exception)
            {
                return false;
            }

            return false;
        }

        private List<Invoice> FindAllInvocies()
        {
            List<Invoice> invoices = new List<Invoice>();
            XDocument doc = DatabaseManager.LoadDBX();
            foreach (XElement invoice in doc.Descendants("invoice"))
                invoices.Add(DBUtils.Element2Invoice(invoice));

            return invoices;
        }
    }
}
